using System;
using System.Collections.Generic;
using System.Text;
using Pg.BioMedics.RatObserver;
using Pg.BioMedics.RatObserver.Database.DAO;
using Pg.BioMedics.RatObserver.Database.DAO.Impl;
using Pg.BioMedics.RatObserver.Database.Model;
using Pg.BioMedics.RatObserver.Util;
using System.IO;

namespace Pg.BioMedics.RatObserver.Archive
{
    public class Archive
    {
        private static IVideoDAO videoDAO = new VideoDAO();
        const String ARCHIVE_DIR = "archive";

        public static VideoInfo Save(String SourceFileName, VideoInfo vi)
        {
            if (videoDAO.extistsVideo(vi))
                throw new VideoNameExistsException(vi.name);
            
            vi.fileName = RandomUtil.genString(20);
            String ext = new FileInfo(SourceFileName).Extension;
            if (ext.Length > 0)
                vi.fileName += ("." + ext);
            vi.removeTime = new DateTime(0);
            //
            if (!Directory.Exists(Path.Combine(Program.currentDirectory, ARCHIVE_DIR)))
                Directory.CreateDirectory(Path.Combine(Program.currentDirectory, ARCHIVE_DIR));

            String targetFile = Program.currentDirectory+ "\\" + ARCHIVE_DIR + "\\" + vi.fileName;
            File.Copy(SourceFileName, targetFile, true);
            //
            videoDAO.saveVideo(vi);
            return vi;
        }

        public static VideoInfo Update(VideoInfo vi)
        {
            if (videoDAO.extistsVideo(vi))
                throw new VideoNameExistsException(vi.name);
            //
            videoDAO.updateVideo(vi);
            return vi;
        }

        public static void Remove(VideoInfo vi)
        {
            File.Delete(ARCHIVE_DIR + "\\" + vi.fileName);
            videoDAO.removeVideo(vi);
        }
    }
}
